document.addEventListener('DOMContentLoaded', () => {
  const container = document.getElementById('carousel-container');
  const cards = container.querySelectorAll('.application-card');
  const prevBtn = document.querySelector('.application-prev');
  const nextBtn = document.querySelector('.application-next');

  const total = cards.length; // 真实卡片总数：10
  // 按照您的要求，克隆数量设置为卡片总数 (10)
  const cloneCount = total;
  // visibleCount 保留原值，但对轮播的核心逻辑不再有直接影响
  const visibleCount = 6;

  const cardWidth = cards[0].offsetWidth;
  const gap = 12;
  const stepWidth = cardWidth + gap;

  // --- 克隆所有卡片到开头和结尾 ---

  // 1. 克隆最后的 cloneCount (10) 张卡片到开头
  // 这将把 R10, R9, ..., R1 克隆到真实卡片序列之前
  for (let i = 0; i < cloneCount; i++) {
    // 当 i=0 时，克隆 cards[0]，并插入到开头，导致最终顺序为 R10, R9, ..., R1
    const clone = cards[total - cloneCount + i].cloneNode(true);
    container.insertBefore(clone, container.firstChild);
  }

  // 2. 克隆开头的 cloneCount (10) 张卡片到结尾
  // 这将把 R1, R2, ..., R10 克隆到真实卡片序列之后
  for (let i = 0; i < cloneCount; i++) {
    const clone = cards[i].cloneNode(true);
    container.appendChild(clone);
  }

  // 起始位置设置为克隆区域之后，即第一个真实的卡片 (索引为 cloneCount)
  let currIndex = cloneCount;
  let isAnimating = false;

  // 设置初始位置
  container.style.transform = `translateX(${-stepWidth * currIndex}px)`;

  function moveToIndex(index) {
    if (isAnimating) return;
    isAnimating = true;
    container.style.transition = 'transform 0.5s ease';
    container.style.transform = `translateX(${-stepWidth * index}px)`;
    currIndex = index;

    container.addEventListener('transitionend', onTransitionEnd);
  }

  function onTransitionEnd() {
    container.removeEventListener('transitionend', onTransitionEnd);

    // 总插槽数量 = cloneCount (10) + total (10) + cloneCount (10) = 30
    // 真实卡片范围：索引 10 到 19

    // 向前循环：当到达末尾的克隆卡片时 (currIndex >= total + cloneCount)，跳回真实卡片的开头
    if (currIndex >= total + cloneCount) {
      container.style.transition = 'none';
      currIndex = cloneCount; // 真实 R1 的索引 (10)
      container.style.transform = `translateX(${-stepWidth * currIndex}px)`;
    }

    // 向后循环：当到达开头的克隆卡片时 (currIndex < cloneCount)，跳回真实的最后一张
    else if (currIndex < cloneCount) {
      container.style.transition = 'none';
      currIndex = total + cloneCount - 1; // 真实 R10 的索引 (19)
      container.style.transform = `translateX(${-stepWidth * currIndex}px)`;
    }
    isAnimating = false;
  }

  function next() {
    if (isAnimating) return;
    // 允许滑动进入克隆区 (索引 20 到 29)
    moveToIndex(currIndex + 1);
  }

  function prev() {
    if (isAnimating) return;
    // 允许滑动进入克隆区 (索引 0 到 9)
    moveToIndex(currIndex - 1);
  }

  prevBtn.addEventListener('click', prev);
  nextBtn.addEventListener('click', next);

  // 自动轮播
  let autoPlayTimer = setInterval(next, 2000);
  container.parentElement.addEventListener('mouseenter', () => clearInterval(autoPlayTimer));
  container.parentElement.addEventListener('mouseleave', () => {
    autoPlayTimer = setInterval(next, 2000);
  });
});